import moment from 'moment'

export function isPaymentPayed(status) {
  return ['s', 'S'].includes(status)
}

export function timeFormating(time, format = 'YYYY-MM-DD HH:mm:ss') {
  return moment(time).format(format)
}

export function numberToCn(num) {
  switch (num) {
    case 1: return '一'
    case 2: return '二'
    case 3: return '三'
    default: return num
  }
}

export function setValueByPath(obj, path, value) {
  return setValue(obj, getPath(path), value)
}

export function getValueByPath(obj, path) {
  return getPath(path).reduce(getValue, obj)
}

export function toNumber(currentValue, oldValue) {
  const value = Number(currentValue)
  if (isNaN(value)) {
    return oldValue
  }
  return value
}

export function toInteger(currentValue, oldValue) {
  const value = toNumber(currentValue, oldValue)
  if (!Number.isInteger(value)) {
    return oldValue
  }
  return value
}

export function toPositiveInteger(currentValue, oldValue) {
  const value = toInteger(currentValue, oldValue)
  if (value < 0) {
    return oldValue
  }
  return value
}

const pathSeparatorRegexp = /\.|\/|:/
const getPath = path => !Array.isArray(path) ? path.split(pathSeparatorRegexp) : path

const setValue = (obj, [key, ...rest], value) => {
  obj = Array.isArray(obj) ? obj.concat() : Object.assign({}, obj)
  obj[key] = rest.length > 0 ? setValue(obj[key], rest, value) : value
  return obj
}
const getValue = (ret, key) => ret[key]